package com.fan.txl.di.module;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.base.txl.http.FileRequestBodyConverterFactory;
import com.f2prateek.rx.preferences2.Preference;
import com.f2prateek.rx.preferences2.RxSharedPreferences;
import com.fan.txl.BuildConfig;
import com.fan.txl.data.auth.Auth;
import com.fan.txl.data.base.Rsp;
import com.fan.txl.ui.FeedsUI;
import com.fan.txl.ui.LoginUI;
import com.fan.txl.utils.Constants;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.Authenticator;
import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**
 * Created by jiajiabao on 17-2-6.
 */

@Module
@SuppressWarnings("unused")
public class NetModule {

    // Dagger will only look for methods annotated with @Provides
    @Provides
    @Singleton
    // Application reference must come from AppModule.class
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    Cache provideCache(Application context) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(context.getCacheDir(), cacheSize);
        /*Request request = new Request.Builder()
                *       .cacheControl(new CacheControl.Builder()
                *           .maxAge(0, TimeUnit.SECONDS)
                *           .build())
        */
        return cache;
    }


    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache
            ,ClearableCookieJar cookieJar
            ,@Named("userAgentInterceptor")Interceptor userAgentInterceptor
            ,@Named("tokenAgentInterceptor")Interceptor tokenAgentInterceptor) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credential = Credentials.basic("clientId", "clientSecret");
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
                .connectTimeout(15, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .readTimeout(30, TimeUnit.SECONDS)
                .cache(cache)
                .cookieJar(cookieJar)
                .addInterceptor(userAgentInterceptor)
                .addInterceptor(tokenAgentInterceptor)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(BuildConfig.DEBUG?HttpLoggingInterceptor.Level.BODY:HttpLoggingInterceptor.Level.NONE))
                .build();

        return okHttpClient;
    }


    @Provides
    @Singleton
    ClearableCookieJar provideCookieJar(Application application) {
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(application));
        return cookieJar;
    }
    @Provides
    @Singleton
    @Named("tokenAgentInterceptor")
    Interceptor provideTokenAgentInterceptor(RxSharedPreferences mRxSharedPreferences) {
        return  new Interceptor(){
            @Override
            public Response intercept(final Chain chain) throws IOException {
                Request request= chain
                        .request()
                        .newBuilder()
                        .header("Authorization", "Bearer "+"5286535a-8c91-4014-8ca5-ee738e06bd2b")
                        .build();
                return chain.proceed(request);

                /*Preference<String> auth=mRxSharedPreferences.getString(Constants.authName);
                auth.asObservable().map(new Function<String, Auth>() {
                    @Override
                    public Auth apply(String s) throws Exception {
                        Rsp<Auth> rsp = JSON.parseObject(s,  new TypeReference<Rsp<Auth>>() {});
                        return rsp.getData();
                    }
                }).subscribe(new Consumer<Auth>() {
                    @Override
                    public void accept(Auth auth) throws Exception {
                        String token = auth.getAccessToken();
                        Request request= chain
                                .request()
                                .newBuilder()
                                .header("Authorization", "Bearer "+token)
                                .build();
                         chain.proceed(request);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                       throwable.printStackTrace();
                    }
                });
                    return null;*/
            }
        };
    }
    @Provides
    @Singleton
    @Named("userAgentInterceptor")
    Interceptor provideUserAgentInterceptor() {
        // ostype 品牌 型号 系统版本号 系统API等级 应用版本 应用版本号 应用版本类型 应用渠道 应用包名称 唯一设备号 网络信息 wifi名称
        //系统版本  android;motorola;XT1079;5.0.2;21;2.1.0;30;deug;office;com.jiajiabao.ucar;XXXXXXXXXXXXX;chinamobile;dev
        //.addInterceptor(new UserAgentInterceptor(UserAgentUtils.getUserAgent()))
        //_builder.addInterceptor(new TokenInterceptor());//token

        return  new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
               Request request= chain
                       .request()
                       .newBuilder()
                       .addHeader("UserAgent","xxxx")
                       .build();
                return chain.proceed(request);
            }
        };
    }



    @Provides
    @Singleton
    Retrofit provideRetrofit(@Named("backend")String backend,OkHttpClient okHttpClient) {
        Retrofit  _retrofit = (new Retrofit.Builder())
                .baseUrl(backend)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(FastJsonConverterFactory.create())
                .addConverterFactory(new FileRequestBodyConverterFactory())
                .client(okHttpClient)
                .build();
        return _retrofit;
    }


}
